#include "../macro.h"
#include <iostream>
#include <unistd.h>
#include <sys/shm.h>
#include <pthread.h>
#include <sys/wait.h>

using std::cout;
using std::endl;

#define N 10000000

struct Data
{
    int num;
    pthread_mutex_t mutex;
};

void test()
{
    int shmid = shmget(1000, 4096, IPC_CREAT | 0600);
    ERR_CHECK(shmid, -1, "shmget")

    Data *data = (Data *)shmat(shmid, nullptr, 0);
    ERR_CHECK(data, (Data *)-1, "shmat")

    // 创建锁资源属性，然后初始化；在设置进程间锁资源共享属性（默认mutex锁资源是线程间共享，进程间私有的）
    // 如果不设置，程序会发生死锁
    pthread_mutexattr_t m_attr;
    pthread_mutexattr_init(&m_attr);
    pthread_mutexattr_setpshared(&m_attr, PTHREAD_PROCESS_SHARED);

    // 动态初始化锁资源
    pthread_mutex_init(&data->mutex, &m_attr);
    data->num = 0;

    if (fork())
    {
        for (int i{}; i < N; i++)
        {
            pthread_mutex_lock(&data->mutex);
            data->num++;
            pthread_mutex_unlock(&data->mutex);
        }

        wait(nullptr);

        printf("num = %d\n", data->num);
    }
    else
    {
        for (int i{}; i < N; i++)
        {
            pthread_mutex_lock(&data->mutex);
            data->num++;
            pthread_mutex_unlock(&data->mutex);
        }
    }
}

int main(int args, char *argv[])
{
    test();
    return 0;
}